package com.liannong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liannong.entity.Product;
import com.liannong.entity.TraceCode;
import com.liannong.exception.BusinessException;
import com.liannong.mapper.ProductMapper;
import com.liannong.mapper.TraceCodeMapper;
import com.liannong.service.TraceCodeService;
import com.liannong.vo.ProductVO;
import com.liannong.vo.TraceCodeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class TraceCodeServiceImpl extends ServiceImpl<TraceCodeMapper, TraceCode> implements TraceCodeService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TraceCodeVO generateTraceCode(String origin) {
        // 生成新的溯源码
        TraceCode traceCode = new TraceCode();
        // 使用UUID生成唯一溯源码
        String code = UUID.randomUUID().toString();
        traceCode.setTraceCode(code);
        traceCode.setOrigin(origin);
        traceCode.setHarvestTime(LocalDateTime.now());
        
        this.save(traceCode);
        return convertToTraceCodeVO(traceCode);
    }

    @Override
    public TraceCodeVO getByTraceCode(String traceCode) {
        QueryWrapper<TraceCode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("trace_code", traceCode);
        TraceCode existingTraceCode = this.getOne(queryWrapper);
        
        if (existingTraceCode == null) {
            throw new BusinessException("溯源码不存在");
        }
        
        return convertToTraceCodeVO(existingTraceCode);
    }
    
    @Override
    public ProductVO getProductByTraceCode(String traceCode) {
        // 直接从产品表查询溯源码
        QueryWrapper<Product> productQuery = new QueryWrapper<>();
        productQuery.eq("traceCode", traceCode);
        Product product = productMapper.selectOne(productQuery);
        
        if (product == null) {
            throw new BusinessException("溯源码不存在");
        }
        
        // 检查产品是否审核通过，如果审核通过但trace_codes表中不存在，则添加
        if (product.getAuditStatus() != null && product.getAuditStatus() == 1) {
            syncTraceCodeToBlockchain(product);
        }
        
        // 转换为ProductVO
        ProductVO productVO = new ProductVO();
        BeanUtils.copyProperties(product, productVO);
        productVO.setProductName(product.getName()); // 前端展示用字段
        
        // 设置审核状态文本
        if (product.getAuditStatus() != null) {
            if (product.getAuditStatus() == 0) {
                productVO.setAuditStatusText("待审核");
            } else if (product.getAuditStatus() == 1) {
                productVO.setAuditStatusText("审核通过");
            } else if (product.getAuditStatus() == 2) {
                productVO.setAuditStatusText("审核拒绝");
            }
        }
        
        return productVO;
    }
    
    private TraceCodeVO convertToTraceCodeVO(TraceCode traceCode) {
        TraceCodeVO vo = new TraceCodeVO();
        vo.setTraceCode(traceCode.getTraceCode());
        vo.setHarvestTime(traceCode.getHarvestTime());
        vo.setOrigin(traceCode.getOrigin());
        return vo;
    }

    /**
     * 同步审核通过的商品信息到溯源码表，为区块链上传做准备
     * @param product 产品信息
     */
    private void syncTraceCodeToBlockchain(Product product) {
        // 检查trace_codes表中是否已存在该溯源码
        QueryWrapper<TraceCode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("trace_code", product.getTraceCode());
        TraceCode existingTraceCode = this.getOne(queryWrapper);
        
        if (existingTraceCode == null) {
            // 不存在则创建新记录
            TraceCode traceCode = new TraceCode();
            traceCode.setTraceCode(product.getTraceCode());
            traceCode.setOrigin(product.getOrigin());
            traceCode.setHarvestTime(product.getHarvestTime());
            
            // 保存到数据库
            this.save(traceCode);
            
            
        }
    }
} 